const API = require('../../../utils/api')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        current:0,
        canvasShow:false,
        material_list:[],
        qrcode:'',
        canvasId:'shareImg',
        pageNum: 1,
        categoryId:'',
        reachBottom: true,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let categoryId = options.id
        this.setData({
            categoryId
        })
        this.get_material_list(5)
        this.creat_wxmini_qrcode()
    },

    /**
     * 轮播切换
     */
    shareImgChange:function(e){
        console.log('轮播切换',e.detail.current)
        this.setData({
            current:e.detail.current
        })
        if( this.data.material_list.length ==  e.detail.current + 1 && this.data.reachBottom ){
            this.setData({
                pageNum: this.data.pageNum + 1
            })
            this.get_material_list(5)
        }
    },

    /**
     * 接口 - 获取海报列表
     */
    get_material_list:function(mediaType){
      let that = this
      API.get_material_list({
        categoryId: that.data.categoryId,
        mediaType: mediaType,
        token: wx.getStorageSync('token'),
        pageNum: that.data.pageNum,
        pageSize: 10
      }).then( res => {
        if( res.code == 200 ){
            let material_list = that.data.material_list
            material_list = [...material_list,...res.rows]
            if( res.rows.length < 10 ){
                that.setData({
                    reachBottom: false
                })
            }
            that.setData({
              material_list
            })
        }
      })
    },

    /**
     * 获取我的二维码
     */
    creat_wxmini_qrcode:function(){
        let that = this
        if( wx.getStorageSync('qrcode') ){
            that.setData({
                qrcode: wx.getStorageSync('qrcode')
            })
            return
        }
        wx.showLoading({
          title: '二维码生成中',
        })
        API.creat_wxmini_qrcode({
            userId: app.globalData.userInfo.id,
            type: '1',
            page: 'pages/share/canvas/canvas'
        }).then( res => {
            if( res.code == 200 ){
                var array = wx.base64ToArrayBuffer(res.msg)
                wx.getFileSystemManager().writeFile({
                    filePath: wx.env.USER_DATA_PATH + "/qrminecode.png",
                    data: array,
                    success: (res) => {
                      that.setData({
                        qrcode: wx.env.USER_DATA_PATH + "/qrminecode.png" //绘制图片使用的图片路径
                      })
                    }
                  })
                console.log( '二维码', wx.env.USER_DATA_PATH + "/qrminecode.png" )

                wx.setStorageSync('qrcode', wx.env.USER_DATA_PATH + "/qrminecode.png" )
            }
            wx.hideLoading()
        })
    },

    /**
     * canvas 画
     */
    getShareImg:function(){
        wx.showLoading({
          title: '生成中',
        })
        //随机canvasid ， 临时方案
        let canvasId = 'shareImg' + Date.parse(new Date())
        this.setData({
            canvasId:canvasId
        })
        console.log(canvasId)
        let imgbg = this.data.material_list[this.data.current].backgroundImgPath
        let qrcode = this.data.qrcode
        this.setData({
            imgbg,
        })
        // console.log( '获取轮播下标',this.data.current, imgbg )

        setTimeout( () => {
            wx.downloadFile({
                url: imgbg, 
                success (res) {
                  if (res.statusCode === 200) {
                    //用于绘图
                    const canvas = wx.createCanvasContext(canvasId)

                    canvas.rect(0, 0,640,990)
                    canvas.setFillStyle('white')
                    canvas.fill()
                    canvas.drawImage(res.tempFilePath, 0, 0, 640, 830)
                    canvas.drawImage(qrcode, 482, 840, 130, 130)
                
                    canvas.setFillStyle('#214081')
                    canvas.font = 'normal bold 32px sans-serif'
                    canvas.fillText('盈联易单配 | 0成本 高佣金',30,888)
                    canvas.font = 'normal bold 24px sans-serif'
                    canvas.fillText('扫码立即加入 ▶',30,936)
                    canvas.draw()
                    wx.hideLoading()
                  }
                  wx.hideLoading()
                }
            })
        },500 )
        
    },
    
    /**
     * 保存分享图
     */
    saveShareImg:function(){
        let that = this
        wx.showLoading({
          title: '保存中',
        })
        setTimeout( () => {
            wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: 640,
                height: 990,
                destWidth: 640 * 750 / wx.getSystemInfoSync().windowWidth, 
                destHeight: 990 * 750 / wx.getSystemInfoSync().windowWidth,
                quality:1,
                canvasId: that.data.canvasId,
                success(res) {
                    console.log(wx.getSystemInfoSync().pixelRatio,res.tempFilePath)
                    wx.saveImageToPhotosAlbum({
                        filePath:res.tempFilePath,
                        success(re) { 
                            wx.showToast({
                              title: '保存成功',
                            })
                            app.creat_records('poster')
                        },
                        fail(){
                            wx.showToast({
                              title: '保存失败',
                              icon:'error'
                            })
                        },
                    })
                    wx.hideLoading()
                }
            })
        },1000)
    },

    /**
     * 打开分享图片弹窗
     */
    showShareImg:function(){
        let that = this
        wx.showLoading({
          title: '保存中',
        })
        setTimeout( () => {
            wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: 640,
                height: 990,
                destWidth: 640 * 750 / wx.getSystemInfoSync().windowWidth, 
                destHeight: 990 * 750 / wx.getSystemInfoSync().windowWidth,
                quality:1,
                canvasId: that.data.canvasId,
                success(res) {
                    console.log(wx.getSystemInfoSync().pixelRatio,res.tempFilePath)
                    wx.showShareImageMenu({
                        path: res.tempFilePath,
                    })
                    wx.hideLoading()
                }
            })
        },1000)
    },

    /**
     * 打开画布
     */
    showCanvas:function(){
        console.log('454353')
        this.getShareImg()
        setTimeout( () => {
            this.setData({
                canvasShow:true
            })
        },500)
    },

    /**
     * 隐藏画布
     */
    hiddenCanvas:function(){
        this.setData({
            canvasShow:false
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        app.creat_records('share') //添加分享日志
    },
    onShareTimeline:function(){
      app.creat_records('share')
    },
})